import { User } from '@/types/user';
import { getCurrentUser } from '@/apis/auth';
import { useQuery, useQueryClient } from '@tanstack/react-query'
import {  isLoggedIn, logout as logoutApi } from '@/apis/auth'

export const AUTH_QUERY_KEY = ['auth', 'current-student']

export function useCurrentStudent() {
  return useQuery({
    queryKey: AUTH_QUERY_KEY,
    queryFn: async (): Promise<User | null> => {
      if (!isLoggedIn()) {
        return null
      }
      return await getCurrentUser()
    },
    enabled: isLoggedIn(), // 只有在已登录时才执行查询
    retry: (failureCount, error: any) => {
      // 如果是认证错误（401），不重试
      if (error?.status === 401 || error?.message?.includes('未登录')) {
        return false
      }
      return failureCount < 1
    },
    staleTime: 5 * 60 * 1000, // 5分钟内认为数据是新鲜的
    gcTime: 10 * 60 * 1000, // 10分钟后清除缓存
  })
}

export function useAuthActions() {
  const queryClient = useQueryClient()

  const login = (token: string) => {
    localStorage.setItem('token', token)
    // 重新获取用户信息
    queryClient.invalidateQueries({ queryKey: AUTH_QUERY_KEY })
  }

  const logout = () => {
    logoutApi()
    // 清除所有查询缓存
    queryClient.clear()
    // 或者只清除认证相关的缓存
    // queryClient.removeQueries({ queryKey: AUTH_QUERY_KEY })
  }

  return { login, logout }
}
